<?php
	require_once('paths.inc');
	require_once(INCLUDE_PATH.'constants.inc');
	require_once(DB_PATH.'db.inc');
	require_once('server_validations.inc');
	require_once('page.inc');
	require_once('security.inc');
	require_once('utils.inc');
	session_start();
	
	// Main section
	select_language();
	
	// Clean the data collected from the user
	if (!validMail($_POST['email'])) {
		$_SESSION['forgot_pass_msg'] = LANG_mail_not_found;    
		header('Location: forgot.php');
		exit();
	}
	$email = $_POST["email"];
	
	// Connect to the MySQL server
	$db = db_connect();
	// Formulate the SQL query find the user
	
	try {
		$user = User::getUserByEmail($db, $email);
	}
	catch (QueryLoadUserException $e) {
		$_SESSION['forgot_pass_msg'] = LANG_mail_not_found;
		header('Location: forgot.php');
		exit();
	}
	
	// get a new session ID (security reasons)
	session_regenerate_id(true);
	
	// Generate a new password
	$new_pass = createRandomPassword();
	$user->password = $new_pass;
	
	try {
		$user->queryChangePassword($db);
	}
	catch (QueryUpdateUserException $e) {
		$_SESSION['forgot_pass_msg'] = LANG_unable_update_pass1;
		header('Location: forgot.php');
		exit();
	}
	catch (QueryWrongVersionException $e) {
		$_SESSION['forgot_pass_msg'] = LANG_unable_update_pass2;
		header('Location: forgot.php');
		exit();
	}
	
	sendEmailForResetPassword($email, LANG_Body_Reset_Password, $new_pass);		 
	$_SESSION['forgot_pass_msg'] = LANG_Forgot_Pass_Sent_Mail;
	header('Location: forgot.php');
?>